package com.wbao.dianniu.logical;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;
import cn.sharesdk.framework.ShareSDK;

import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.alibaba.sdk.android.media.MediaService;
import com.alibaba.sdk.android.media.WantuService;
import com.alibaba.wxlib.util.SysUtil;
import com.baidu.mapapi.SDKInitializer;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;
import com.wbao.dianniu.db.DbManager;
import com.wbao.dianniu.im.InitHelper;
import com.wbao.dianniu.R;

import dalvik.system.DexClassLoader;

public class DnApplication extends MultiDexApplication {
	private static final String TAG = DnApplication.class.getSimpleName();
	 public static final String NAMESPACE = "openim";
	 private static Context sContext;
	 public static WantuService wantuService;
	 
		public static Context getContext(){
			return sContext;
		}
		
		@Override
		protected void attachBaseContext(Context base) {
			super.attachBaseContext(base);
			MultiDex.install(this);
		}
	
	@Override
	public void onCreate() {
		super.onCreate();
//		dexTool();
		// todo
		// Application.onCreate中，首先执行这部分代码，以下代码固定在此处，不要改动，这里return是为了退出Application.onCreate！！！
		if (mustRunFirstInsideApplicationOnCreate()) {
			// todo 如果在":TCMSSevice"进程中，无需进行openIM和app业务的初始化，以节省内存
			return;
		}
		
		// 初始化云旺SDK
		InitHelper.initYWSDK(this);

		// 初始化多媒体SDK，小视频和阅后即焚功能需要使用多媒体SDK
		AlibabaSDK.asyncInit(this, new InitResultCallback() {
			@Override
			public void onSuccess() {
				Log.e(TAG, "-----initTaeSDK----onSuccess()-------");
				MediaService mediaService = AlibabaSDK.getService(MediaService.class);
				mediaService.enableHttpDNS(); // 果用户为了避免域名劫持，可以启用HttpDNS
				mediaService.enableLog(); // 在调试时，可以打印日志。正式上线前可以关闭
			}

			@Override
			public void onFailure(int code, String msg) {
				Log.e(TAG, "-------onFailure----msg:" + msg + "  code:" + code);
			}
		});
		
		// 顽兔初始化
		WantuService.enableHttpDNS(); // 可选。为了避免域名劫持，建议开发者启用HttpDNS
		WantuService.enableLog(); //在调试时，可以打开日志。正式上线前可以关闭
		 
		wantuService = WantuService.getInstance();
		wantuService.asyncInit(this);
		
		// 初始化图片缓存 Android-Universal-Image-Loader
//		initImageLoader();
		
		// 注意该方法要再setContentView方法之前实现 初始化 地图插件
		SDKInitializer.initialize(getApplicationContext());
		
		// 初始化分享组件，小内存消耗，可以多次初始化
		ShareSDK.initSDK(this , getResources().getString(R.string.share_app_key));
		//初始化数据库
		DbManager dbManager = new DbManager(this);
		dbManager.initDataBase();
		
		// SDK在统计Fragment时，需要关闭Activity自带的页面统计，
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
		 MobclickAgent.openActivityDurationTrack(false);
		 MobclickAgent.enableEncrypt(true);
		 MobclickAgent.setScenarioType(this, EScenarioType.E_UM_NORMAL);
		 
	}
	
	private boolean mustRunFirstInsideApplicationOnCreate() {
		//必须的初始化
		SysUtil.setApplication(this);
		sContext = getApplicationContext();
		return SysUtil.isTCMSServiceProcess(sContext);
	}
	
	private void dexTool() {
        File dexDir = new File(getFilesDir(), "dlibs");
        dexDir.mkdir();
        File dexFile = new File(dexDir, "libs.apk");
        File dexOpt = new File(dexDir, "opt");
        dexOpt.mkdir();
        try {
           InputStream ins = getAssets().open("libs.apk");
           if (dexFile.length() != ins.available()) {
               FileOutputStream fos = new FileOutputStream(dexFile);
               byte[] buf = new byte[4096];
               int l;
               while ((l = ins.read(buf)) != -1) {
                   fos.write(buf, 0, l);
               }
               fos.close();
           }
           ins.close();
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
 
        ClassLoader cl =getClassLoader();
        ApplicationInfo ai =getApplicationInfo();
        String nativeLibraryDir= null;
        if(Build.VERSION.SDK_INT > 8) {
           nativeLibraryDir = ai.nativeLibraryDir;
        } else {
           nativeLibraryDir = "/data/data/" + ai.packageName +"/lib/";
        }
        DexClassLoader dcl = new DexClassLoader(dexFile.getAbsolutePath(),
               dexOpt.getAbsolutePath(), nativeLibraryDir, cl.getParent());
        try {
           Field f = ClassLoader.class.getDeclaredField("parent");
           f.setAccessible(true);
           f.set(cl, dcl);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }
	
	
}
